package es.mgil.whoWantsToBeAMillonaire.handlers;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import es.mgil.whoWantsToBeAMillonaire.R;
import es.mgil.whoWantsToBeAMillonaire.activities.Scores;
import es.mgil.whoWantsToBeAMillonaire.runnables.GetFriendsScoresRunnable;
import es.mgil.whoWantsToBeAMillonaire.util.HighScore;
import es.mgil.whoWantsToBeAMillonaire.util.HighScoreList;
import es.mgil.whoWantsToBeAMillonaire.util.MillonaireItemizedOverlay;
import es.mgil.whoWantsToBeAMillonaire.views.ExtendedMapView;

public class GetFriendsScoresHandler extends Handler {
	private Context context;

	public GetFriendsScoresHandler(Context context) {
		this.context = context;
	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case GetFriendsScoresRunnable.GET_FRIENDS_SCORES_ERROR_EMPTY:
			// a user name should be set
			Toast.makeText(context, R.string.score_friends_error_empty,
					Toast.LENGTH_LONG).show();
			break;
		case GetFriendsScoresRunnable.GET_FRIENDS_SCORES_ERROR_SERVER:
			// error occurred in the server
			Toast.makeText(context, R.string.score_friends_error_server,
					Toast.LENGTH_LONG).show();
			break;
		case GetFriendsScoresRunnable.GET_FRIENDS_SCORES_ERROR_NO_FRIENDS:
			// no friends
			Toast.makeText(context, R.string.score_friends_error_no_friends,
					Toast.LENGTH_LONG).show();
			break;
		case GetFriendsScoresRunnable.GET_FRIENDS_SCORES_OK:
			// friends loaded correctly, so update the map
			updateMap((HighScoreList) msg.obj);
			Toast.makeText(context, R.string.score_friends_ok,
					Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
	}

	/**
	 * Update the map with the list of high scored retrieved
	 */
	private void updateMap(HighScoreList highScoresList) {
		Scores scores = (Scores) context;
		ExtendedMapView map = scores.getMapView();

		List<Overlay> mapOverlays = map.getOverlays();
		Drawable drawable = context.getResources().getDrawable(
				R.drawable.ic_launcher);
		MillonaireItemizedOverlay itemizedOverlay = new MillonaireItemizedOverlay(
				context, drawable);

		// draw an overlay in the map for every high score
		for (HighScore hs : highScoresList.getScores()) {
			GeoPoint point = new GeoPoint((int) (hs.getLatitude() * 1e6),
					(int) (hs.getLongitude() * 1e6));
			OverlayItem item = new OverlayItem(point, hs.getName(),
					String.valueOf(hs.getScoring()));
			itemizedOverlay.addOverlay(item);
			mapOverlays.add(itemizedOverlay);
		}
	}
}